﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace WSServer
{
    public class WSSocketMessagePool
    {
        const int MONITOR_DURATION = 180 * 1000;
        const int MESSAGE_CACHE_THREASHOLD = 100;
        static object locker = new object();
        private List<WSResponse> responses { get; set; }
        private Timer messageMonitor { get; set; }
        public string poolId { get; set; }

        public WSSocketMessagePool(string _poolId)
        {
            poolId = poolId;
            responses = new List<WSResponse>();
            messageMonitor = new Timer((o) =>
            {
                WSStorage storage = new WSStorage();
                this.CacheResponsesToStorage(storage);
            }, null, MONITOR_DURATION, MONITOR_DURATION);
        }
        public void didReceiveMessageRecip(WSResponseReceip receip)
        {
            responses.RemoveAll(r => r.messageId == receip.messageId);
        }
        public void addMessage(WSResponse response)
        {
            lock(locker)
            {
                responses = new List<WSResponse>();
            }
        }
        public void CacheResponsesToStorage(WSStorage storage)
        {
            lock(locker)
            {
                if(responses.Count >= MESSAGE_CACHE_THREASHOLD)
                {
                    storage.store(responses, poolId);
                }
            }
        }
    }
}
